package cyx.example.ddd.application.order.event;

import cyx.example.ddd.domain.shared.DomainEvent;
import cyx.example.ddd.domain.shared.DomainEventPublisher;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

/**
 * Spring Event 领域事件发布器实现
 * 
 * 使用Spring的ApplicationEventPublisher发布领域事件
 * 适用于单机应用或简单的分布式场景
 */
@Slf4j
@Primary
@Component
@RequiredArgsConstructor
public class OrderEventPublisher implements DomainEventPublisher {

    private final ApplicationEventPublisher eventPublisher;

    @Override
    public void publish(DomainEvent event) {
        try {
            log.debug("发布领域事件: {} - {}", event.getEventType(), event.getEventId());
            eventPublisher.publishEvent(event);
            log.debug("领域事件发布成功: {}", event.getEventId());
        } catch (Exception e) {
            log.error("发布领域事件失败: {} - {}", event.getEventType(), event.getEventId(), e);
            // 在实际项目中，可能需要：
            // 1. 记录失败事件
            // 2. 重试机制
            // 3. 告警通知
        }
    }
}